package com.opensource.msgui.ctl.demo.controller.v1.service;

import com.opensource.msgui.ctl.demo.controller.v1.config.MQSource;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;

import javax.annotation.Resource;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SendService {
    @Resource
    private MQSource source;

    /**
     * 发送简单消息
     * @param msg
     */
    public void send(String msg) {
        source.output1().send(MessageBuilder.withPayload(msg).build());
    }

    /**
     * 发消息时添加标签
     * @param msg
     * @param tag
     * @param <T>
     */
    public <T> void sendWithTags(T msg, String tag){
        Message message = MessageBuilder.createMessage(msg, new MessageHeaders(Stream.of(tag).collect(Collectors.toMap(str -> MessageConst.PROPERTY_TAGS, String::toString))));
        source.output1().send(message);
    }

    /**
     * 发送一个对象消息
     * @param msg
     * @param tag
     * @param <T>
     */
    public <T> void sendObject(T msg, String tag){
        Message message = MessageBuilder.withPayload(msg)
                .setHeader(MessageConst.PROPERTY_TAGS, tag)
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build();
        source.output1().send(message);
    }

    /**
     * 发送事务消息
     * @param msg
     * @param num
     * @param <T>
     */
    public <T> void sendTransactionMessage(T msg, int num){
        MessageBuilder builder = MessageBuilder.withPayload(msg)
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
        builder.setHeader("test", String.valueOf(num));
        source.output2().send(builder.build());
    }

    public void sendMassiveMessage(String msg) {
        source.output3().send(MessageBuilder.withPayload(msg).build());
    }
}
